#include "GBMors.h"
#include "reg52.h" 

sbit SCL=P2^1;
sbit SDA=P2^0;
void delay10us(void)   //误差 0us
{
    unsigned char a,b;
    for(b=1;b>0;b--)
        for(a=2;a>0;a--);
}

void i2cstart(){
	SDA = 1;
	delay10us();
	SCL = 1;
	delay10us();
	SDA = 0;
	delay10us();
	SCL = 0;
	delay10us();
}

void i2cstop(){
	SDA = 0;
	delay10us();
	SCL = 1;
	delay10us();
	SDA = 1;
	delay10us();
}


unsigned char i2cSend(unsigned char dat){
	unsigned char a = 0,b ;
	for(a = 0 ;a < 8 ;a ++){
		SDA = dat >> 7;
		dat = dat << 1;
		delay10us();
		SCL = 1;
		delay10us();
		SCL = 0;
		delay10us();
		}
		SDA = 1;
		delay10us();
		SCL = 1;
		while(SDA){
				b ++;
			if(b > 200){
			SCL = 0;
				delay10us();
				return 0;
			}
			
		}
		SCL = 0;
		delay10us();
		return 1;//发送成功
}

unsigned char i2cRead(){
	unsigned char a = 0,dat = 0;
	SDA = 1;
	delay10us();
	for(a = 0; a<8; a++){
			SCL = 1;
			delay10us();
			dat <<= 1;
			dat |= SDA;
			delay10us();
			SCL = 0;
			delay10us();
	}
	return dat;
}

void at24C02Write(unsigned char addr,unsigned char dat){
	i2cstart();
	i2cSend(0xa0);
	i2cSend(addr);
	i2cSend(dat);
	i2cstop();
}

unsigned char at24C02Read(unsigned char addr){
	unsigned char num;
	i2cstart();
	i2cSend(0xa0);
	i2cSend(addr);
	i2cstart();
	i2cSend(0xa1);
	num = i2cRead();
	i2cstop();
	return num;
}

